<?php

namespace teach\service;

use Yii;

class Cart
{

    /**
     * 加入购物车
     * @param $map
     * @return int
     */
    public function cartAdd($map)
    {
        return Yii::$app->db->createCommand()->insert('mall_cart', $map)->execute();
    }

    /**
     * 物品是否已经有在购物车里了
     * @param $condition
     * @return false|null|string
     */
    public function cartHaving($condition)
    {
        $sql = "SELECT COUNT(*) FROM mall_cart WHERE " . $condition;
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }

    /**
     * 购物车添加重复物品
     * @param $condition
     * @param $count
     * @return int
     */
    public function cartAddUpdate($condition,$count)
    {
        $sql = "UPDATE mall_cart SET count = count + {$count} WHERE {$condition}";
        return  Yii::$app->db->createCommand($sql)->execute();

    }

    /**
     * 获取购物车
     * @param $condition
     * @return array
     */
    public function cartsList($condition)
    {
        $sql = "SELECT * FROM mall_cart WHERE {$condition} ORDER BY create_time DESC";
        $res =  Yii::$app->db->createCommand($sql)->queryAll();
        $res_data = [];
        if ($res) {
            foreach ($res as $_key => $_val) {
                $product = Yii::$app->db->createCommand("SELECT p.title, p.img, s.product_no, s.stock, p.freight, p.mid, p.label,s.value, s.price, p.update_time as p_update_time, p.create_time as p_create_time, s.img as simg FROM mall_product_specs as s LEFT JOIN mall_product as p ON p.id = s.pid WHERE  s.id = {$_val['sku_id']}")->queryOne();
                $_val['title'] = $product['title'];
                if ($product['simg']) {
                    $images = explode(',', $product['simg']);
                    $_val['img'] = $images[0];
                } else {
                    $_val['img'] = $product['img'];
                }
                $_val['product_no'] = $product['product_no'];
                $_val['stock'] = $product['stock'];
                $_val['freight'] = $product['freight'];
                $_val['mid']  = $product['mid'];
                $_val['label'] = $product['label'];
                $_val['value'] = $product['value'];
                $_val['price'] = $product['price'];
                $res_data[$_key] = $_val;
            }
            return $res_data;
        } else {
            return $res;
        }
    }

    /**
     * 购物车产出商品
     * @param $condition
     * @return int
     */
    public function cartDelete($condition)
    {
        return Yii::$app->db->createCommand()->delete('mall_cart',$condition)->execute();
    }

    /**
     * 修改购物车数量
     * @param $map
     * @param $mapper
     * @return int
     */
    public function cartChange($map, $mapper)
    {
        $sql = "UPDATE mall_cart SET {$map} WHERE {$mapper}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

}